package cn.ultrarisk.scadmin.manager.biz.monitor.service;

import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.scadmin.manager.biz.monitor.dao.SolrCacheMonitorDAO;
import cn.ultrarisk.scadmin.manager.biz.monitor.entity.SolrCacheMonitor;
import cn.ultrarisk.scadmin.manager.biz.solr.context.SolrCacheType;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrReplica;
import cn.ultrarisk.scadmin.manager.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class SolrCacheMonitorService {
    @Autowired
    private SolrCacheMonitorDAO solrCacheMonitorDAO;

    public SolrCacheMonitor createBySolrInfo(SolrReplica replica, String cacheTypeStr, JsonUtil.MapWrapper cacheMap, Long createTime) {
        SolrCacheType cacheType = SolrCacheType.get(cacheTypeStr);

        SolrCacheMonitor monitor = new SolrCacheMonitor(replica, cacheType);
        if (SolrCacheType.FIELD_CACHE == cacheType) {
            monitor.setEntriesCount(cacheMap.getIntByPath("stats.entries_count"));
            monitor.setInsanityCount(cacheMap.getIntByPath("stats.insanity_count"));
        } else {
            monitor.setLookups(cacheMap.getLongByPath("stats.cumulative_lookups"));
            monitor.setHits(cacheMap.getLongByPath("stats.cumulative_hits"));
            monitor.setInserts(cacheMap.getLongByPath("stats.cumulative_hits"));
            monitor.setEvictions(cacheMap.getLongByPath("stats.cumulative_inserts"));
            monitor.setSize(cacheMap.getLongByPath("stats.cumulative_evictions"));
        }

        monitor.setCreateTime(createTime);
        solrCacheMonitorDAO.create(monitor);
        return monitor;
    }

    /**
     * 清除过期的SolrCache监控数据
     *
     * @query expiredTime
     */
    public void clearExpiredData(long expiredTime) {
        Query query = Query.ltQuery(SolrCacheMonitor.CREATE_TIME, expiredTime);
        solrCacheMonitorDAO.delete(query);
    }
}